package com.desire.controller.common;

import com.desire.bean.common.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author LittleDesire
 * @description
 * @date 2022-05-10 周二 16:53
 * @since 17
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionController extends BaseController {
    /**
     * 处理 方法参数无效异常
     *
     * @param e MethodArgumentNotValidException
     * @return 异常信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBean handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.toString());
        Map<String, Object> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        // 获取出错的字段名 参数名
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        Iterator<FieldError> iterator = fieldErrorList.iterator();
        while (iterator.hasNext()) {
            FieldError error = iterator.next();
            map.put(error.getField(), error.getDefaultMessage());
        }
        return fail("校验失败", map);
    }
}
